package com.cloudweb.oa.controller;

import cn.js.fan.security.SecurityUtil;
import cn.js.fan.security.ThreeDesUtil;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.cache.DepartmentCache;
import com.cloudweb.oa.cache.DeptUserCache;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.config.JwtProperties;
import com.cloudweb.oa.entity.Department;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.exception.ValidateException;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.IDepartmentService;
import com.cloudweb.oa.service.IDeptUserService;
import com.cloudweb.oa.service.IUserService;
import com.cloudweb.oa.service.SsoService;
import com.cloudweb.oa.utils.ConstUtil;
import com.cloudweb.oa.utils.JwtUtil;
import com.cloudweb.oa.utils.SysProperties;
import com.cloudweb.oa.utils.SysUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudweb.oa.vo.UserVO;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.Config;
import com.redmoon.oa.flow.MyActionDb;
import com.redmoon.oa.flow.WorkflowUtil;
import com.redmoon.oa.person.UserDb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class SsoController {

    @Autowired
    HttpServletRequest request;

    @Autowired
    SysUtil sysUtil;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    SysProperties sysProperties;

    @Autowired
    UserCache userCache;

    @Autowired
    IUserService userService;

    @Autowired
    IDepartmentService departmentService;

    @Autowired
    IDeptUserService deptUserService;

    @Autowired
    DepartmentCache departmentCache;

    @Autowired
    DeptUserCache deptUserCache;

    @Autowired
    SsoService ssoService;

    @RequestMapping(value = "/public/sso/syncOrg", produces={MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public Result<Object> syncOrg(HttpServletResponse response, @RequestParam String info) {
        String authToken = ssoService.syncOrg(info);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", authToken);
        // response.setHeader(jwtProperties.getHeader(), authToken);
        return new Result<>(jsonObject);
    }

    /**
     * 从第三方系统跳转（旧版）
     * /public/jump?mode=1&token=userName&data={type=module, moduleCode=模块的编码}
     * @param token
     * @param mode
     * @param data
     * @param model
     * @return
     */
    @RequestMapping(value = "/public/sso/jump")
    public String jump(String token, @RequestParam(required = true, defaultValue = "0") Integer mode, String data, Model model) {
        String userName;
        if (mode == 0) {
            String desKey = Config.getInstance().getKey();
            String plainText = ThreeDesUtil.decrypthexstr(desKey, token);
            String[] ary = StrUtil.split(plainText, "\\|"); // 格式为：userName|timestamp
            if (ary == null || ary.length != 2) {
                model.addAttribute("msg", "token 格式非法");
                return "th/error/error";
            }

            String timestamp = ary[1];
            Date d = DateUtil.parse(timestamp);
            // 大于 30 秒则超时
            if ((d.getTime() - (new Date()).getTime())/1000 > 30) {
                model.addAttribute("msg", "token超时");
                return "th/error/error";
            }
            userName = ary[0];
        }
        else {
            userName = token;
        }

        String type;
        JSONObject json = JSONObject.parseObject(data);
        if (!json.containsKey("type")) {
            model.addAttribute("msg", "参数非法");
            return "th/error/error";
        }
        else {
            type = json.getString("type");
        }

        authUtil.doLoginByUserName(request, userName);

        if ("module".equals(type)) {
            if (json.containsKey("moduleCode")) {
                String moduleCode = json.getString("moduleCode");
                return "redirect:/visual/moduleListPage.do?moduleCode=" + moduleCode;
            }
            else {
                model.addAttribute("msg", type + " 参数非法");
                return "th/error/error";
            }
        }

        model.addAttribute("msg", type + " 非法");
        return "th/error/error";
    }
}
